package com.kx.sms.service.impl;

import com.kx.sms.mapper.SmsHisMapper;
import com.kx.sms.pojo.SmsHis;
import com.kx.sms.pojo.SmsHisExample;
import com.kx.sms.service.SmsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author Sun
 * @Date 2021/7/19 19:39
 */
@Service
public class SmsServiceImpl implements SmsService {

    /**
     * 超时时间5分钟
     */
    private static final int TIMEOUT = 1000 * 60 * 5;

    @Resource
    private SmsHisMapper smsHisMapper;

    @Override
    public int saveSms(String phoneNo, String code, Integer typeId) {
        SmsHis smsHis = new SmsHis();
        smsHis.setPhoneno(phoneNo);
        smsHis.setCode(code);
        smsHis.setServiceTypeId(typeId);
        smsHis.setTime(System.currentTimeMillis());
        int result = smsHisMapper.insertSelective(smsHis);
        return result;
    }

    @Override
    public int checkSms(String phoneNo, String code, Integer typeId) {
        //1.查询数据库中的验证码和前台传来的验证码进行对比
        SmsHisExample example = new SmsHisExample();
        SmsHisExample.Criteria criteria = example.createCriteria();
        criteria.andPhonenoEqualTo(phoneNo);
        criteria.andServiceTypeIdEqualTo(typeId);
        //根据时间进行降序排列，要最新的一条数据
        example.setOrderByClause("'time' desc");
        List<SmsHis> smsHisList = smsHisMapper.selectByExample(example);
        if (smsHisList != null && smsHisList.size() > 0) {
            SmsHis smsHis = smsHisList.get(0);
            if (code.equals(smsHis.getCode())) {
                //比较当前时间和数据空中最新的一条验证码的时间，判断是否超时
                if(System.currentTimeMillis()-smsHis.getTime()<=TIMEOUT){
                    return 1;
                }else {
                    //超时过期了
                    return 0;
                }
            } else {
                //验证码错误
                return 2;
            }
        }else {
            return 2;
        }
    }
}
